﻿define(function (require, exports, module) {

    var manager = {};
    require('ezdesk/utility/datetime');
    var service = require('ezdesk/utility/service');

    var GETFEEDS_TIMER_INTERVAL = 2000;
    var isGettingFeeds = false;

    var initDate = new Date('1900','1','1');

    function getTimemark() {
        var timeMark = localStorage.getItem('TimeMark');
        return timeMark ? timeMark : initDate.toEpoch();
    }
    function setTimemark(dateTime) {
        localStorage.setItem('TimeMark', dateTime);
    }
    var timemark = getTimemark();

    function getFeedsCallback() {
        console.log('getFeedsCallback');
        if (!isGettingFeeds) {
            console.log('sending requests to get feeds... timemark: ' + timemark);
            isGettingFeeds = true;
            service.AllJsonFeedsBetweenDate(
                function (e) {
                    isGettingFeeds = false;
                    if (e.length != 0) {
                        // 找出update的变化，也作为callback传回去
                        var feedsWithNewUpdateOn = _.select(e, function (feed) {
                            return feed.UpdateOn > timemark
                        });

                        manager.newFeedsCallback(e, feedsWithNewUpdateOn);
                        var maxUpdateOn = _.max(e, function (item) { return item.UpdateOn }).UpdateOn;
                        var maxLastChangeOn = _.max(e, function (item) { return item.LastChangeOn }).LastChangeOn;
                        timemark = Math.max(maxLastChangeOn, maxUpdateOn) + 1;
                        setTimemark(timemark);


                        console.log('i got something, we have ' + e.length + ' more feeds. Timemark is updated: ' + timemark);
                    } else {
                        console.log('nothing new');
                    }
                },
                { fromEpoch: timemark, toEpoch: new Date().toEpoch() }
            );
        }
    }


    var notificationTimerId = 0;
    manager.start = function () {
        console.log('start notification manager');
        setInterval(getFeedsCallback, GETFEEDS_TIMER_INTERVAL);
    };
    manager.newFeedsCallback = function (newfeeds, feedsWithNewUpdateOn) {
    };

    module.exports = manager;
});